class AhobAddController
  
  def self.respond_to model, request, config, store
    # 1. We'll start with ahob.org/plant, which will offer a list of models to choose from
    # 2. Handler will read the model and redirect to ahob.org/plant/[model]
    # 3. Handler will then validate the model and load a for with the additional key field since
    # we can't source it from the url until we have saved it.
    
    # req needs to ascertain if the [model] portion is present
    # If not, we go for option 1.
    # If so, we go for option 2.
    req = request.env['REQUEST_ARRAY'][-1]
    if (req == '/plant')
      if (request.env['REQUEST_METHOD'] == 'POST')
        response = Rack::Response.new
        response.redirect request.env['REQUEST_ARRAY'].join('/') << '/' << request.POST['model']
        return response
      else
        models = store.get_model_list
        target = request.env['REQUEST_ARRAY'].join('/')
        response = Rack::Response.new
        response.headers['Content-Type'] = 'text/html'
        response.write ERB.new(store.get_value('/model/AhobAdd/base_template')).result(binding)
        return response
      end
    end
    
    # we need to create a new model as the edit model is not required
    model = AModelBanana.new store
    model.load [req], true # load expects a url array
    
    obj = AClockworkBanana.new store, model
    error = []
    saved = false
    if request.env['REQUEST_METHOD'] == 'POST'
      # TODO: data validation
      key = request.POST['key']
      obj.turn key, true, true
      #TODO: when a field doesn't exist in the model
      request.POST.each do |k, v|
        begin
          obj.send("#{k.to_sym}=", v) unless k == 'key'
        rescue
          error.push "Received invalid post variable #{k}."
        end
      end
      if key == ''
        error << 'You <em>must</em> provide a key.'
      elsif obj.is_valid?
        # TODO: error handling
        store.create model, obj, key
        response = Rack::Response.new
        response.redirect 'http://ahob.org/finger' << key
        return response
      else
        error.concat obj.errors unless obj.is_valid?
      end
    else 
      obj.turn '/new', true, true
    end
    
    # load template and return ('unused' variables *are* used via binding)
    form = load_form model, obj
    title = key
    target = request.env['REQUEST_ARRAY'].join('/')
    response = Rack::Response.new
    response.headers['Content-Type'] = 'text/html'
    response.write ERB.new(store.get_value('/model/AhobAdd/template')).result(binding)
    return response
  end
  
  private
  
  
#TODO: centralize this as we use it in edit.rb & add.rb
  def self.load_form model, obj
    form = "<fieldset>\n"
    model.fields.each do |field|
      form << get_input(field, model.fieldtypes[field], obj.send(field.to_sym))
    end
    form << "</fieldset>\n"
  end
  
  def self.get_input field, type, value=''
    res = ''
    case type
      when 'Text'
        res << "  <label for=\"#{field}\">#{field}</label>\n"
        res << "  <textarea name=\"#{field}\" id=\"#{field}\">#{value.split("\r\n").join("\n")}</textarea>\n"
      else
        res << "  <label for=\"#{field}\">#{field}</label>\n"
        res << "  <input type=\"text\" name=\"#{field}\" id=\"#{field}\" value=\"#{value}\" />\n"
    end
    return res
  end
  
end